package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.CustomerInfo;
import com.ruoyi.system.domain.CustomerChat;
import com.ruoyi.system.mapper.CustomerChatMapper;
import com.ruoyi.system.mapper.CustomerUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Service
public class StatusCheckService {

    private static final Logger log = LoggerFactory.getLogger(StatusCheckService.class);

    //    @Autowired
    private final static Map<String, ScheduledFuture<?>> taskMap = new HashMap<>();
    private final TaskScheduler taskScheduler;

    @Autowired
    private CustomerUserMapper customerUserMapper;
    @Autowired
    private Environment env;

    @Autowired
    RedisCache redisCache;

    @Autowired
    private WaURLService waURLService;

    @Autowired
    private CustomerChatMapper customerChatMapper;

    //    private long startTime = System.currentTimeMillis();
    private Map<String, Long> startTimeMap = new HashMap<>();

    public StatusCheckService(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    // 这个方法是手动调用的任务
    // 启动定时任务，并传入 contactNumber 作为标识
    public void startManualCheck(String contactNumber) {
        try {
            // 如果之前已经有该 contactNumber 的任务在运行，取消它
            if (taskMap.containsKey(contactNumber)) {
                ScheduledFuture<?> existingTask = taskMap.get(contactNumber);
                if (existingTask != null && !existingTask.isCancelled()) {
                    existingTask.cancel(false);  // 取消之前的任务
                    log.info("Cancelled existing task for contact number: {}", contactNumber);
                }
            }

            // 启动新的定时任务，每10秒检查一次
            ScheduledFuture<?> scheduledTask = taskScheduler.scheduleAtFixedRate(() -> checkClientStatus(contactNumber), 10000);
            taskMap.put(contactNumber, scheduledTask);  // 将新任务添加到 map 中
            long startTime = System.currentTimeMillis();
            startTimeMap.put(contactNumber, startTime);
            log.info("Started new task for contact number: {}", contactNumber);
        } catch (Exception e) {
            log.error("startManualCheck existing task for contact number: {}", contactNumber);
        }
    }

    // 定时检查任务
    private void checkClientStatus(String contactNumber) {
        try {
            String url = waURLService.getContactNumberURL(contactNumber, "apiSevicePath.getClientReadyStatus");
            String rspStr = HttpUtils.sendGet(url + contactNumber);
//            log.info("rspStr:" + rspStr);
            if (!rspStr.contains("CONNECTED")) {
                long startTime = startTimeMap.get(contactNumber);
                long elapsedTime = (System.currentTimeMillis() - startTime) / 1000 / 60; // 计算已经过去的分钟数
                if (elapsedTime >= 5) { // 如果15分钟内还是false
                    String deleteUrl = waURLService.getContactNumberURL(contactNumber, "apiSevicePath.deleteClient");
                    HttpUtils.sendGet(deleteUrl + contactNumber);

                    cancelTask(contactNumber);
                    CustomerInfo user = new CustomerInfo();
                    user.setContactNumber(contactNumber);
//                    user.setLinkStatus("1");
                    customerUserMapper.updateLinkStatus(user);
                }
            } else if (!rspStr.contains(contactNumber)) {
                log.info("contactNumber:" + rspStr);
                cancelTask(contactNumber);
                CustomerInfo user = new CustomerInfo();
                user.setContactNumber(contactNumber);
                user.setLinkStatus("号码不一致");
                customerUserMapper.updateLinkStatus(user);
            } else {
                log.info("CONNECTED contactNumber:" + rspStr);
                cancelTask(contactNumber);
                CustomerInfo user = new CustomerInfo();
                user.setContactNumber(contactNumber);
                user.setLinkStatus("0");
                customerUserMapper.updateLinkStatus(user);
            }
        } catch (Exception e) {
            log.error("checkClientStatus existing task for contact number: {}", contactNumber);
        }
    }

    //获取头像，并更新粉丝信息
    public void updateClientInfo(String contactNumber) {
        List<CustomerInfo> customerChatList = customerChatMapper.selectChatListContactNumber(contactNumber);
        for (CustomerInfo user : customerChatList) {
//            user.getClientNumber()
        }

    }


    // 取消指定 contactNumber 的定时任务
    public void cancelTask(String contactNumber) {
        try {
            ScheduledFuture<?> scheduledTask = taskMap.get(contactNumber);
            if (scheduledTask != null && !scheduledTask.isCancelled()) {
                scheduledTask.cancel(false);
                log.info("Scheduled task for contact number {} has been cancelled.", contactNumber);
            }
        } catch (Exception e) {
            log.error("Cancelled existing task for contact number: {}", contactNumber);
        }
    }

    // 查看是否有任务在运行
    public boolean isTaskRunning(String contactNumber) {
        return taskMap.containsKey(contactNumber) && !taskMap.get(contactNumber).isCancelled();
    }


    public int checkGroupCode(String time,String groupCheckData) {
        CustomerInfo user = customerUserMapper.selectUserByContactName("对接号");
        // 如果之前已经有该 contactNumber 的任务在运行，取消它
        String key = "code_" + user.getContactNumber();
        try {
            if (taskMap.containsKey(key)) {
                ScheduledFuture<?> existingTask = taskMap.get(key);
                if (existingTask != null && !existingTask.isCancelled()) {
                    existingTask.cancel(false);  // 取消之前的任务
                    log.info("Cancelled checkGroupCode task for contact number: {}", key);
                }
            }

            if (StringUtils.isEmpty(time)) {
                time = "3600";
            }

            // 启动新的定时任务，每1个小时检查一次
            ScheduledFuture<?> scheduledTask = taskScheduler.scheduleAtFixedRate(() -> checkCode(user.getContactNumber(),groupCheckData), Integer.valueOf(time) * 1000);
            taskMap.put(key, scheduledTask);  // 将新任务添加到 map 中
            long startTime = System.currentTimeMillis();
            startTimeMap.put(key, startTime);
            log.info("开启获取验证码后的回访功能: {}", key);
        } catch (Exception e) {
            log.error("开启获取验证码后的回访功能失败: {}", key);
        }
        return 1;
    }

    // 定时检查任务
    private void checkCode(String contactNumber,String groupCheckData) {
        try {
            String groupMessagesUrl = waURLService.getContactNumberURL(contactNumber, "apiSevicePath.getGroupMessages");
            String param = "id=" + contactNumber;
            String encodedString = URLEncoder.encode("打粉", StandardCharsets.UTF_8.toString());
            String groupName = "&groupName=" + encodedString + "&";
            if (StringUtils.isEmpty(groupCheckData)){
                groupCheckData = "100";
            }
            String limitNumber = "limitNumber=" + Integer.valueOf(groupCheckData);
            param = param + groupName + limitNumber;
            String res = HttpUtils.sendGet(groupMessagesUrl, param);
            try {
                JSONArray jsonArray = JSON.parseArray(res); // 解析为 JSONArray
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//                    JSONObject idObject = jsonObject1.getJSONObject("_data"); // 获取 id 对象

                    String from = jsonObject1.getString("from"); // 从 id 中获取 from
                    String body = jsonObject1.getString("body"); // 从 id 中获取 body
                    String to = jsonObject1.getString("to"); // 从 id 中获取 to
                    String timestamp = jsonObject1.getString("timestamp"); // 从 id 中获取 timestamp
                    log.info("body is {}", body);

                    if (from.contains("120363357873925122")) {
                        log.info("from is {}", from);
                        log.info("to is {}", to);
                        if (body.contains("\n")) {
                            String[] lines = body.split("\n");
                            // 遍历并打印每一行
                            for (String line : lines) {
                                sendCheckCode(line);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("JSON解析错误: {}", e.getMessage());
            }
        } catch (Exception e) {
            log.error("contactNumber existing task for contact number: {}", contactNumber);
        }
    }

    private void sendCheckCode(String number) {
        try {
            Object num = redisCache.getCacheObject("check_num:" + number);
            if (StringUtils.isNull(num)) {
                String url = env.getProperty("apiSevicePath.checkCode");
                String param = "number=" + number;
                HttpUtils.sendGet(url, param);
                log.info("url:" + url + "  sendCheckCode:" + number);
                redisCache.setCacheObject("check_num:" + number, 1);
            }
        } catch (Exception e) {
            log.error("JSON解析错误: {}", e.getMessage());
        }
        return;
    }


}
